{% extends "base.html" %}
{% block content %}
<div class="container" style="width: 100%; margin:auto;">
    <!-- 搜索+返回按钮水平对齐 -->
    <div style="display: flex; align-items: center; gap: 12px; margin-bottom: 18px;">
      <form action="{{ url_for('search_bucket', bucket_name=bucket_name, path=path) }}"
            style="flex:1; display:flex; align-items:center;">
        <input class="form-control" name="search" placeholder="{{ search_param }}" autocomplete="off" autofocus type="text"
               style="flex:1; margin-right:8px; height:36px;" />
        <button class="btn waves-effect waves-light" type="submit" name="action"
                style="height:36px; line-height:36px; padding:0 16px;">
          Search
        </button>
      </form>
      <a href="{{ url_for('index') }}" class="btn-small blue" style="white-space:nowrap; height:36px; line-height:36px;">返回 Bucket</a>
      {% if path %}
      {% set parent_path = path.rstrip('/').rsplit('/', 1)[0] %} {# 获取上一级路径 #}
      <a href="{{ url_for('view_bucket', bucket_name=bucket_name, path=parent_path) }}"
         class="btn-small grey lighten-1" style="white-space:nowrap; height:36px; line-height:36px;">
        上一级
      </a>
      {% endif %}
    </div>

    <!-- 面包屑导航 -->
    <div class="breadcrumb" style="font-size:1em; margin-bottom:18px;">
        <a href="{{ url_for('view_bucket', bucket_name=bucket_name) }}" style="font-weight:bold; color:#1976d2;">{{ bucket_name }}</a>
        {% if path %}
            {% set parts = path.rstrip('/').split('/') %}
            {% set curr_path = "" %}
            {% for part in parts %}
                <span class="separator" style="color:#888; margin:0 6px;">/</span>
                {% set curr_path = curr_path + part + '/' %}
                <a href="{{ url_for('view_bucket', bucket_name=bucket_name, path=curr_path) }}" style="color:#1976d2;">{{ part }}</a>
            {% endfor %}
        {% endif %}
    </div>

    <!-- 操作区一行一个表单 -->
    <div class="card-panel" style="margin-bottom:24px;">
      <form action="{{ url_for('create_folder', bucket_name=bucket_name, path=path) }}" method="post" style="margin-bottom:12px; display:flex; align-items:center; gap:8px;">
        <input type="text" name="folder_name" placeholder="输入新目录名" required style="width:180px; height:36px; margin-bottom:0;">
        <button type="submit" class="btn-small blue" style="height:36px; line-height:36px;">新建目录</button>
      </form>
      <form action="{{ url_for('upload_file', bucket_name=bucket_name, path=path) }}" method="post" enctype="multipart/form-data" style="margin-bottom:12px; display:flex; align-items:center; gap:8px;">
        <label for="file-input-files" class="btn-small green" style="height:36px; line-height:36px; cursor:pointer; margin-bottom:0;">选择文件</label>
        <input type="file" name="files" id="file-input-files" multiple required style="display:none;">
        <span id="file-names-display-files" style="flex:1;">未选择文件</span>
        <button type="submit" class="btn-small green" style="height:36px; line-height:36px;">上传文件</button>
      </form>
      <form action="{{ url_for('upload_file', bucket_name=bucket_name, path=path) }}" method="post" enctype="multipart/form-data" style="display:flex; align-items:center; gap:8px;">
        <label for="file-input-folders" class="btn-small blue" style="height:36px; line-height:36px; cursor:pointer; margin-bottom:0;">选择文件夹</label>
        <input type="file" name="files" id="file-input-folders" multiple webkitdirectory directory required style="display:none;">
        <span id="file-names-display-folders" style="flex:1;">未选择文件夹</span>
        <button type="submit" class="btn-small blue" style="height:36px; line-height:36px;">上传文件夹</button>
      </form>
    </div>

    <!-- 批量下载操作按钮 -->
    <div class="card-panel" style="margin-bottom:24px; padding:12px; display:flex; align-items:center; gap:12px;">
        <label>
            <input type="checkbox" id="select-all-checkbox" onclick="selectAll(this)" class="filled-in">
            <span>全选</span>
        </label>
        <button onclick="batchDownload()" class="btn waves-effect waves-light blue">批量下载选中项</button>
    </div>

    <!-- 分页 -->
    {% if total_pages > 1 %}
    <div class="pagination center-align" style="margin: 18px 0;">
        <ul class="pagination">
            {% if current_page > 1 %}
            <li class="waves-effect"><a href="?page={{ current_page - 1 }}&search={{ search_param }}"><i class="material-icons">chevron_left</i></a></li>
            {% else %}
            <li class="disabled"><a href="#!"><i class="material-icons">chevron_left</i></a></li>
            {% endif %}

            {% for p in range(1, total_pages + 1) %}
                {% if p == current_page %}
                <li class="active blue"><a href="?page={{ p }}&search={{ search_param }}">{{ p }}</a></li>
                {% else %}
                <li class="waves-effect"><a href="?page={{ p }}&search={{ search_param }}">{{ p }}</a></li>
                {% endif %}
            {% endfor %}

            {% if current_page < total_pages %}
            <li class="waves-effect"><a href="?page={{ current_page + 1 }}&search={{ search_param }}"><i class="material-icons">chevron_right</i></a></li>
            {% else %}
            <li class="disabled"><a href="#!"><i class="material-icons">chevron_right</i></a></li>
            {% endif %}
        </ul>
    </div>
    {% endif %}

    <!-- 文件夹 列表 -->
    <h5>文件夹</h5>
    <ul class="collection">
        {% for item in contents if item.type == "folder" %}
        <li class="collection-item" style="display:flex; align-items:center; gap:8px;">
            <!-- 文件夹选择复选框 -->
            <label>
                <input type="checkbox" name="selected_items" value="{{ item.name }}" class="filled-in"> {# 统一 name 为 selected_items #}
                <span></span>
            </label>
            {# 文件夹链接需要处理 current_path，如果 path 为空，item.name 就是顶级文件夹 #}
            {% set full_folder_path = (path + item.name)|urlencode if path else item.name|urlencode %}
            <a href="{{ url_for('view_bucket', bucket_name=bucket_name, path=item.name) }}" style="flex:1;">
                {{ item.name }}
            </a>
            <!-- 文件夹下载按钮 (保留) -->
            {# 注意：这里使用 onclick 调用 JS 函数，而不是直接的 form submit #}
            <button type="button" class="btn-small grey lighten-1" onclick="downloadFolder('{{ item.name }}')">下载</button>

            <!-- 删除、重命名操作 -->
            <form action="{{ url_for('delete_folder', bucket_name=bucket_name, path=item.name) }}" method="post" style="display:inline;">
                <button type="submit" class="btn-small red" onclick="return confirm('确定要删除整个目录及其所有内容吗？此操作不可逆！');">删除</button>
            </form>
            <form action="{{ url_for('rename_file', bucket_name=bucket_name, path=item.name) }}" method="post" style="display:inline; display:flex; align-items:center; gap:4px;">
                <input type="text" name="new_name" placeholder="新目录名" style="width:100px; margin-bottom:0; height:36px;" required>
                <button type="submit" class="btn-small orange" style="height:36px; line-height:36px;">重命名</button>
            </form>
        </li>
        {% endfor %}
    </ul>

    <!-- 文件 列表 -->
    <h5>文件</h5>
    {% set image_exts = ['jpg','jpeg','png','gif','webp'] %}
    {% set video_exts = ['mp4','webm','ogg'] %}
    {% set text_exts = ['txt', 'csv', 'md', 'json', 'xml', 'log', 'html', 'css', 'js', 'py', 'c', 'cpp', 'java', 'go', 'sh'] %}
    <ul class="collection">
        {% for item in contents if item.type != "folder" %}
        {% set ext = item.name.rsplit('.', 1)[-1]|lower %}
        <li class="collection-item" style="display:flex; align-items:center; gap:8px;">
            <!-- 文件选择复选框 -->
            <label>
                <input type="checkbox" name="selected_items" value="{{ item.name }}" class="filled-in"> {# 统一 name 为 selected_items #}
                <span></span>
            </label>
            <span style="flex:1;">
{#                <i class="material-icons" style="vertical-align:middle; margin-right:4px;">insert_drive_file</i>#}
                <a href="{{ url_for('download_file', bucket_name=bucket_name, path=item.name) }}" download="{{ item.name }}" target="_blank">{{ item.name }}</a>
                {% if ext in image_exts or ext in video_exts or ext in text_exts %}
                  {# 预览链接应指向后端 preview 路由 #}
                  <a href="javascript:void(0);" class="btn-small orange"
                     onclick="previewFile('/preview?bucket_name={{ bucket_name|urlencode }}&path={{ item.name|urlencode }}', '{{ ext }}')">预览</a>
                {% endif %}
                <span style="color:#888; font-size:0.9em;">
                    {# 这里应用过滤器 #}
                    | {{ item.date_modified | format_datetime }} | {{ item.size }}
                </span>
            </span>
            <!-- 删除、重命名操作 -->
            <form action="{{ url_for('delete_file', bucket_name=bucket_name, path=item.name) }}" method="post" style="display:inline;">
                <button type="submit" class="btn-small red" onclick="return confirm('确定要删除文件吗？');">删除</button>
            </form>
            <form action="{{ url_for('rename_file', bucket_name=bucket_name, path=item.name) }}" method="post" style="display:inline; display:flex; align-items:center; gap:4px;">
                <input type="text" name="new_name" placeholder="新名称" style="width:100px; margin-bottom:0; height:36px;" required>
                <button type="submit" class="btn-small orange" style="height:36px; line-height:36px;">重命名</button>
            </form>
        </li>
        {% endfor %}
    </ul>

    <!-- 预览弹窗HTML -->
    <div id="preview-modal" style="position:fixed; left:0; top:0; width:100vw; height:100vh; display:none;
        align-items:center; justify-content:center; background:rgba(0,0,0,0.7); z-index:9999;">
      <div id="preview-content" style="background:#fff; padding:20px; border-radius:8px; max-width:80vw; max-height:80vh; position:relative;">
        <span onclick="closePreview()" style="position:absolute; right:12px; top:8px; cursor:pointer; font-size:1.5em;">✖</span>
        <!-- 动态插入图片或视频或文本内容 -->
      </div>
    </div>
</div>

<script>
    // 初始化 Materialize CSS 的复选框样式
    document.addEventListener('DOMContentLoaded', function() {
        M.FormSelect.init(document.querySelectorAll('select')); // 如果有用到select
        M.Checkbox.init(document.querySelectorAll('input[type="checkbox"]')); // 初始化所有checkbox
    });

    // 文件上传：显示选中的文件数量/名称
    document.getElementById('file-input-files').addEventListener('change', function(e) {
      let displaySpan = document.getElementById('file-names-display-files');
      if (e.target.files.length > 0) {
        if (e.target.files.length === 1) {
            displaySpan.textContent = e.target.files[0].name;
        } else {
            displaySpan.textContent = `已选择 ${e.target.files.length} 个文件`;
        }
      } else {
        displaySpan.textContent = '未选择文件';
      }
    });

    // 文件夹上传：显示选中的文件夹名称
    document.getElementById('file-input-folders').addEventListener('change', function(e) {
      let displaySpan = document.getElementById('file-names-display-folders');
      if (e.target.files.length > 0) {
        // webkitdirectory 选择的文件夹，第一个文件的 webkitRelativePath 包含了文件夹名
        const firstFile = e.target.files[0];
        const folderName = firstFile.webkitRelativePath.split('/')[0];
        displaySpan.textContent = `已选择文件夹: ${folderName} (${e.target.files.length}个文件)`;
      } else {
        displaySpan.textContent = '未选择文件夹';
      }
    });

    function previewFile(url, ext) {
        var modal = document.getElementById('preview-modal');
        var content = document.getElementById('preview-content');
        // 清空除关闭按钮以外内容
        content.innerHTML = '<span onclick="closePreview()" style="position:absolute; right:12px; top:8px; cursor:pointer; font-size:1.5em;">✖</span>';
        ext = ext.toLowerCase();

        // 支持更多文本文件类型
        const text_exts = ['txt', 'csv', 'md', 'json', 'xml', 'log', 'html', 'css', 'js', 'py', 'c', 'cpp', 'java', 'go', 'sh'];

        if(['jpg','jpeg','png','gif','webp'].includes(ext)) {
            var img = document.createElement('img');
            img.src = url;
            img.style.maxWidth = '70vw';
            img.style.maxHeight = '70vh';
            img.style.objectFit = 'contain';
            content.appendChild(img);
        } else if(['mp4','webm','ogg'].includes(ext)) {
            var video = document.createElement('video');
            video.src = url;
            video.controls = true;
            video.style.maxWidth = '70vw';
            video.style.maxHeight = '70vh';
            content.appendChild(video);
        } else if (text_exts.includes(ext)) {
            fetch(url)
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }
                    return response.text();
                })
                .then(text => {
                    var pre = document.createElement('pre');
                    pre.textContent = text;
                    pre.style.whiteSpace = 'pre-wrap';
                    pre.style.wordBreak = 'break-all';
                    pre.style.maxHeight = '70vh';
                    pre.style.overflowY = 'auto';
                    content.appendChild(pre);
                })
                .catch(error => {
                    console.error('Error fetching text file for preview:', error);
                    content.innerHTML += '<p style="color:red;">无法加载文本内容进行预览: ' + error.message + '</p>';
                });
        }
        else {
            content.innerHTML += '<p>暂不支持预览该类型文件</p>';
        }
        modal.style.display = 'flex';
    }
    function closePreview() {
        document.getElementById('preview-modal').style.display = 'none';
    }

    // 全选/全不选功能
    function selectAll(source) {
        // 选择所有 name="selected_items" 的复选框
        checkboxes = document.querySelectorAll('input[name="selected_items"]');
        for(var i=0, n=checkboxes.length; i<n; i++) {
            checkboxes[i].checked = source.checked;
            // Materialize CSS 需要手动更新其 visual state
            if (source.checked) {
                checkboxes[i].nextElementSibling.classList.add('checked');
            } else {
                checkboxes[i].nextElementSibling.classList.remove('checked');
            }
        }
    }

    // 批量下载功能
    function batchDownload() {
        var selectedItems = []; // 更改变量名以反映其包含文件和文件夹
        // 选择所有 name="selected_items" 且被选中的复选框
        var checkboxes = document.querySelectorAll('input[name="selected_items"]:checked');
        checkboxes.forEach(function(checkbox) {
            // 这里的 value 应该是完整的 S3 Key，例如 "path/to/file.txt" 或 "path/to/folder/"
            selectedItems.push(checkbox.value);
        });

        if (selectedItems.length === 0) {
            alert("请至少选择一个文件或文件夹进行批量下载。"); // 更新提示信息
            return;
        }

        var form = document.createElement('form');
        form.method = 'POST';
        form.action = '{{ url_for("batch_download_items") }}'; // 指向新的批量下载路由
        form.style.display = 'none';

        var bucketInput = document.createElement('input');
        bucketInput.type = 'hidden';
        bucketInput.name = 'bucket_name';
        bucketInput.value = '{{ bucket_name }}';
        form.appendChild(bucketInput);

        // 添加 current_path 隐藏域，用于后端生成ZIP文件名
        var currentPathInput = document.createElement('input');
        currentPathInput.type = 'hidden';
        currentPathInput.name = 'current_path';
        currentPathInput.value = '{{ path }}'; // 传递当前路径
        form.appendChild(currentPathInput);

        // 将所有选中的文件/文件夹路径合并成一个字符串传递，因为后端需要获取一个字符串
        var selectedItemsInput = document.createElement('input');
        selectedItemsInput.type = 'hidden';
        selectedItemsInput.name = 'selected_items'; // 后端通过 request.form.get('selected_items') 获取
        selectedItemsInput.value = selectedItems.join(','); // 逗号分隔的字符串
        form.appendChild(selectedItemsInput);

        document.body.appendChild(form);
        form.submit();
    }

    // 文件夹下载功能 (通过POST请求发送数据) - 保留此函数
    function downloadFolder(folderPath) {
        var form = document.createElement('form');
        form.method = 'POST';
        form.action = '{{ url_for("download_folder") }}'; // 指向文件夹下载的路由
        form.style.display = 'none';

        var bucketInput = document.createElement('input');
        bucketInput.type = 'hidden';
        bucketInput.name = 'bucket_name';
        bucketInput.value = '{{ bucket_name }}';
        form.appendChild(bucketInput);

        var folderPathInput = document.createElement('input');
        folderPathInput.type = 'hidden';
        folderPathInput.name = 'folder_path'; // 后端通过 request.form.get('folder_path') 获取
        folderPathInput.value = folderPath; // 确保是 S3 中的完整文件夹路径（以/结尾）
        form.appendChild(folderPathInput);

        document.body.appendChild(form);
        form.submit();
    }
</script>

{% endblock %}